package com.itany.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author:石小俊
 * @Date: 2022/12/22 13:37
 * @Version:1.0-SNAPSHOT
 * @Description: 黑名单过滤器
 * 要求在当前过滤器中设置初始化参数
 * 将所有黑名单的人员的ip地址在初始化参数中进行配置
 * 且黑名单的人员数量不固定,随时可能变更
 * 在功能实现之后,后期仍然可能会变更黑名单
 * 要求后期变更黑名单时只需要改动初始化参数即可,无需修改实现代码
 * 如果是黑名单用户,无法访问我们的服务,其他人正常访问
 */
//@WebFilter(urlPatterns = "/*",initParams = {
//    @WebInitParam(name = "blackList",value = "127.0.0.1,192.168.7.8")
//})
public class BlackListFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("BlackListFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取初始化参数中所有的ip地址
        String blackList = config.getInitParameter("blackList");
        // 在配置初始化参数时,我们将所有的黑名单的ip地址写在了同一个数据中
        // 这些ip通过逗号分隔了
        // 可以通过逗号分隔,将这些ip地址还原出来
        String[] ips = blackList.split(",");

        // 获取访问者的ip
        String ip = request.getRemoteAddr();
        // 遍历黑名单
        for(String s : ips){
            // 如果访问者的ip在黑名单中
            if(ip.equals(s)){
                // 不允许访问
                response.setContentType("text/html;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.print("<h1 style='color:red;'>您是黑名单用户,请联系客服解除黑名单</h1>");
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
